package com.tanhua.server.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.RelativeDateFormat;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.service.QuanZiMQService;
import com.tanhua.server.service.QuanZiService;
import com.tanhua.server.service.UserInfoService;
import com.tanhua.server.service.UserService;
import com.tanhua.server.vo.CommentVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.QuanZiVo;
import com.tanhua.server.vo.VisitorsVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Service
public class QuanZiServiceImpl implements QuanZiService {
    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;
    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private PicUploadService picUploadService;
    @Autowired
    private QuanZiMQService quanZiMQService;
    @Override
    public PageResult queryPublishList(Integer page, Integer pageSize) {
        PageResult result=new PageResult();
        result.setPagesize(pageSize);
        result.setPage(page);
        User user = UserThreadLocal.get();
        PageInfo<Publish> pageInfo = this.quanZiApi.queryPublishList(user.getId(), page, pageSize);
        List<Publish> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)){
            return result;
        }
        //准备封装返回的数据
        List<QuanZiVo> quanZiVoList = this.getQuanZiVos(records);
        result.setItems(quanZiVoList);
        return result;
    }



    private void fillUserInfoToQuanZiVo(UserInfo userInfo, QuanZiVo quanZiVo) {
       //id为动态id,各自都有而且用处不同应排除
        BeanUtil.copyProperties(userInfo,quanZiVo,"id");
        quanZiVo.setGender(userInfo.getSex().toString().toLowerCase());//改小写
        quanZiVo.setTags(StringUtils.split(userInfo.getTags(), ','));


        quanZiVo.setCommentCount(Convert.toInt(this.quanZiApi.queryCommentCount(quanZiVo.getId()))); //TODO 评论数
        quanZiVo.setDistance("1.2公里"); //TODO 距离
        User user = UserThreadLocal.get();
        quanZiVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(),quanZiVo.getId())?1:0); // 是否点赞（1是，0否）
        quanZiVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(quanZiVo.getId()))); // 点赞数
        quanZiVo.setHasLoved(this.quanZiApi.queryUserIsLove(user.getId(),quanZiVo.getId())?1:0); // 是否喜欢（1是，0否）
        quanZiVo.setLoveCount(Convert.toInt(this.quanZiApi.queryLoveCount(quanZiVo.getId()))); // 喜欢数

    }

    @Override
    public String savePublish(String textContent, String location, String latitude, String longitude, MultipartFile[] multipartFile) {

        Publish publish=new Publish();
        publish.setLatitude(latitude);
        publish.setLocationName(location);
        publish.setLongitude(longitude);
        publish.setText(textContent);
        //获取发布者信息
        User user=UserThreadLocal.get();

        publish.setUserId(user.getId());
        publish.setSeeType(1);

        List<String> picUrls=new ArrayList<>();
        for (MultipartFile file : multipartFile) {
            PicUploadResult upload = this.picUploadService.upload(file);
            picUrls.add(upload.getName());
        }
        publish.setMedias(picUrls);
        String publishId = this.quanZiApi.savePublish(publish);
        if (StrUtil.isNotEmpty(publishId)){
            this.quanZiMQService.publishMsg(publishId);
        }
        return publishId;
    }

    @Override
    public PageResult queryRecommendPublishList(Integer page, Integer pageSize) {
        PageResult result=new PageResult();
        result.setPagesize(pageSize);
        result.setPage(page);
        User user = UserThreadLocal.get();
        PageInfo<Publish> pageInfo = this.quanZiApi.queryRecommendPublishList(user.getId(), page, pageSize);
        List<Publish> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)){
            return result;
        }
        //准备封装返回的数据
        List<QuanZiVo> quanZiVoList = getQuanZiVos(records);
        result.setItems(quanZiVoList);
        return result;
    }

    @Override
    public Long loveComment(String publishId) {
        User user=UserThreadLocal.get();
        Boolean aBoolean = this.quanZiApi.loveComment(user.getId(), publishId);
        if(aBoolean){
            this.quanZiMQService.lovePublishMsg(publishId);
            return this.quanZiApi.queryLoveCount(publishId);
        }
        return null;
    }

    @Override
    public Long disLoveComment(String publishId) {
        User user=UserThreadLocal.get();
        Boolean aBoolean = this.quanZiApi.disLoveComment(user.getId(), publishId);
        if(aBoolean){
            this.quanZiMQService.disLovePublishMsg(publishId);
            return this.quanZiApi.queryLoveCount(publishId);
        }
        return null;
    }

    @Override
    public Long disLikeComment(String publishId) {
        User user=UserThreadLocal.get();
        Boolean aBoolean = this.quanZiApi.disLikeComment(user.getId(), publishId);
        if(aBoolean){
            this.quanZiMQService.disLikePublishMsg(publishId);
            return this.quanZiApi.queryLikeCount(publishId);
        }
        return null;
    }

    @Override
    public Long likeComment(String publishId) {
        User user=UserThreadLocal.get();
        Boolean aBoolean = this.quanZiApi.likeComment(user.getId(), publishId);
        if(aBoolean){
            this.quanZiMQService.likePublishMsg(publishId);
            return this.quanZiApi.queryLikeCount(publishId);
        }
        return null;
    }

    //查询所有评论
    @Override
    public PageResult queryCommentList(String publishId, Integer page, Integer pageSize) {
        PageResult pageResult=new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        User user = UserThreadLocal.get();
        PageInfo<Comment> pageInfo = this.quanZiApi.queryCommentList(publishId, page, pageSize);
        List<Comment> records = pageInfo.getRecords();
        if(CollUtil.isEmpty(records)){
            return  pageResult;
        }
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoByUserIdList(userIds);
        List<CommentVo> list=new ArrayList<>();
        for (Comment record : records) {
            CommentVo commentVo=new CommentVo();
            commentVo.setId(record.getId().toHexString());
            commentVo.setContent(record.getContent());
            commentVo.setCreateDate(DateUtil.format(new Date(record.getCreated()),"HH:mm"));
            commentVo.setHasLiked(this.quanZiApi.queryUserIsLike(user.getId(),record.getId().toHexString())?1:0);
            commentVo.setLikeCount(Convert.toInt(this.quanZiApi.queryLikeCount(record.getId().toHexString())));
            for (UserInfo userInfo : userInfos) {
                if (userInfo.getUserId().longValue()==record.getUserId().longValue()){
                    commentVo.setAvatar(userInfo.getLogo());
                    commentVo.setNickname(userInfo.getNickName());
                    break;
                }
            }
            list.add(commentVo);
        }

        pageResult.setItems(list);

        return pageResult;
    }

    @Override
    public Boolean saveComments(String publishId, String content) {
        User user = UserThreadLocal.get();
        Boolean result = this.quanZiApi.saveComment(user.getId(), publishId, content);

            if(result){
                //发消息
                this.quanZiMQService.commentPublishMsg(publishId);
            }
        return result;
    }

    @Override
    public QuanZiVo queryById(String publishId) {
        Publish publish = this.quanZiApi.queryPublishById(publishId);
        if (publish == null) {
            return null;
        }
        //发消息
        this.quanZiMQService.queryPublishMsg(publishId);
        return this.getQuanZiVos(Arrays.asList(publish)).get(0);
    }

    private List<QuanZiVo> getQuanZiVos(List<Publish> records) {
        List<QuanZiVo> quanZiVoList = new ArrayList<>();
        for (Publish record : records) {
//            封装部分数据进返回对象
            QuanZiVo quanZiVo = new QuanZiVo();
            quanZiVo.setId(record.getId().toHexString()
            );
            quanZiVo.setTextContent(record.getText());
            quanZiVo.setUserId(record.getUserId());
            quanZiVo.setImageContent(record.getMedias().toArray(new String[]{}));
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated())));
            quanZiVoList.add(quanZiVo);
        }
        //所有发布数据的所有用户的id
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        //查询对应id的所有详细数据方便封装
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoByUserIdList(userIds);
        for (QuanZiVo quanZiVo : quanZiVoList) {
            for (UserInfo userInfo : userInfos) {
                if (userInfo.getUserId().longValue() == quanZiVo.getUserId().longValue()) {
                    this.fillUserInfoToQuanZiVo(userInfo, quanZiVo);
                    break;
                }
            }
        }
        return quanZiVoList;
    }

    @Override
    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        //查询数据
        PageInfo<Publish> pageInfo = this.quanZiApi.queryAlbumList(userId, page, pageSize);
        if(CollUtil.isEmpty(pageInfo.getRecords())){
            return pageResult;
        }

        //填充数据
        pageResult.setItems(this.getQuanZiVos(pageInfo.getRecords()));

        return pageResult;
    }

    @Override
    public List<VisitorsVo> queryVisitorsList() {
        User user = UserThreadLocal.get();
        List<Visitors> visitors = this.visitorsApi.queryMyVisitor(user.getId());
        if (CollUtil.isEmpty(visitors)){
            return ListUtil.empty();
        }
        List<Object> visitorUserId = CollUtil.getFieldValues(visitors, "visitorUserId");
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoByUserIdList(visitorUserId);
        List<VisitorsVo> visitorsVoList=new ArrayList<>();
        VisitorsVo visitorsVo=null;
        for (Visitors visitor : visitors) {
            for (UserInfo userInfo : userInfos) {
                if(ObjectUtil.equals(visitor.getVisitorUserId(),userInfo.getUserId())){
                    visitorsVo=new VisitorsVo();
                    visitorsVo.setAge(userInfo.getAge());
                    visitorsVo.setAvatar(userInfo.getLogo());
                    visitorsVo.setGender(userInfo.getSex().getValue()==1?"man":"woman");
                    visitorsVo.setId(userInfo.getUserId());
                    visitorsVo.setNickname(userInfo.getNickName());
                    visitorsVo.setTags(userInfo.getTags().split(","));
                    visitorsVo.setFateValue(visitor.getScore().intValue());

                    visitorsVoList.add(visitorsVo);
                    break;
                }

            }

        }
        return visitorsVoList;
    }
}
